<template>
	<div id="map-container">
		
	</div>
	<div class="search">
		<i-input size="large" placeholder="景点、酒店、美食等" style="width: 400px" :value.sync="searchKeyWords" @keyup.enter='doSearch'></i-input>
		<i-button type="primary" @click="doSearch">
      <Icon type="search" color="#ffffff" size="24"></Icon>
  	</i-button>
	</div>
	<div class="toolbar">
		<go-toolbar :map="map"></go-toolbar>
	</div>
	<div class="locate">
		<i-button type="ghost" size="small" @click="getMyLocation">
			<Icon type="android-locate" color="#3399ff" size="18"></Icon>
		</i-button>
	</div>
	<div id="detail-panel">
		<b>{{scopeProperties['"name"']}}</b>
		<ul>
			<li v-if="scopeProperties.address"><b>地址：</b><span>{{scopeProperties.address}}</span></li>
			<li v-if="scopeProperties.scope_type"><b>景区类型：</b><span>{{scopeProperties.scope_type}}</span></li>
			<li v-if="scopeProperties.overall"><b>评分：</b><span>{{scopeProperties.overall}}</span></li>
			<li v-if="scopeProperties.shop_hours"><b>开放时间：</b><span>{{scopeProperties.shop_hours}}</span></li>
			<li v-if="scopeProperties.scope_grade"><b>景区评级：</b><span>{{scopeProperties.scope_grade}}</span></li>
			<li v-if="scopeProperties.description"><b>简介：</b><span>{{scopeProperties.description}}</span></li>
		</ul>
	</div>
</template>

<script>
import turf from '@turf/turf'
//import mapboxgl from 'mapbox-gl/dist/mapbox-gl-dev.js'
import MapboxGeocoder from 'mapbox-gl-geocoder'
import util from './util.js'
export default {
	methods:{
		getMyLocation:function(){
			if (navigator.geolocation) { 
	      navigator.geolocation.getCurrentPosition(this.showPosition,this.showError); 
	    } else { 
	      this.$Message.warning("该浏览器不支持获取地理位置。"); 
			}
		},
		showPosition:function(position){
			var myLocation = [position.coords.longitude,position.coords.latitude];
			if(!this.map.getSource("myLocation")){
				var source = {
					type:"geojson",
					data:turf.point(myLocation)
				}
				this.map.addSource("myLocation",source);
				this.map.addLayer({
				  id:"myLocation-circle-stroke",
				  type:"circle",
				  source:"myLocation",
				  "paint":{
				    'circle-radius': 7,
				    'circle-color': '#006cd8'
				  }
				});
				this.map.addLayer({
				  id:"myLocation-circle",
				  type:"circle",
				  source:"myLocation",
				  "paint":{
				    'circle-radius': 5,
      			'circle-color': '#3bb2d0'
				  }
				});	
			}else{
				var newPointSource = turf.point(myLocation);
				this.map.getSource("myLocation").setData(newPointSource);
			}
    	this.map.setCenter(myLocation);
    	var url = "https://api.mapbox.com/geocoding/v5/mapbox.places/"+myLocation[0]+","+myLocation[1]+".json?access_token="+util.gl_accessToken;
    	this.$http({url:url,method:'GET'}).then(function(res){
    		var feature = res.body.features[0];
    		var popup = new mapboxgl.Popup({closeOnClick:false})
    		  .setLngLat(myLocation)
    		  .setText(feature.place_name)
    		  .addTo(this.map);
    	},function(res){

    	});
		},
		showError:function(error){
			switch(error.code) 
	    { 
        case error.PERMISSION_DENIED: 
          this.$Message.error("用户拒绝对获取地理位置的请求。");
          break; 
        case error.POSITION_UNAVAILABLE: 
            this.$Message.error("位置信息是不可用的。"); 
            break; 
        case error.TIMEOUT: 
            this.$Message.error("请求用户地理位置超时。");
            break; 
        case error.UNKNOWN_ERROR: 
            this.$Message.error("未知错误。"); 
            break; 
	    }
		},
		doSearch:function(){
      var searchUrl = "https://api.mapbox.com/geocoding/v5/mapbox.places/"+this.searchKeyWords+".json?access_token="+util.gl_accessToken;
      this.$http({url:searchUrl,method:'GET'}).then(function(res){
        var results = res.body.features; 
        this.searchResults = results;
        var features = [];
        var left=180,right=-180,top=-90,bottom=90;
        for(var i = 0;i<results.length;i++){
        	var center = results[i].center;
        	if(i===0){
        		var popup = new mapboxgl.Popup()
        		  .setLngLat(center)
        		  .setText(results[0].text)
        		  .addTo(this.map);
        		this.popup = popup;
        	}
          left = center[0]<left?center[0]:left;
          right = center[0]>right?center[0]:right;
          top = center[1]>top?center[1]:top;
          bottom = center[1]<bottom?center[1]:bottom;
          features.push(turf.point(center,{id:i}));
        }
        this.map.fitBounds([[left, bottom], [right, top]],{padding:200});
        var resultGeojson = turf.featureCollection(features);
        if(!this.map.getSource("searchResult")){
          var source = {
            type:"geojson",
            data:resultGeojson
          }
          this.map.addSource("searchResult",source);
          this.map.addLayer({
            id:"searchResult-circle-stroke",
            type:"circle",
            source:"searchResult",
            "paint":{
              'circle-radius': 7,
              'circle-color': '#006cd8'
            }
          });
          this.map.addLayer({
            id:"searchResult-circle",
            type:"circle",
            source:"searchResult",
            "paint":{
              'circle-radius': 5,
              'circle-color': '#ff0000'
            }
          }); 
          this.map.on("click",this.mapSearchClick);
          this.map.on("mousemove",this.searchMouseMove);
        }else{
          this.map.getSource("searchResult").setData(resultGeojson);
        }
      },function(res){

      });
		},
		mapSearchClick:function(e) {
			// Use queryRenderedFeatures to get features at a click event's point
	    // Use layer option to avoid getting results from other layers
	    var features = this.map.queryRenderedFeatures(e.point, { layers: ['searchResult-circle-stroke','searchResult-circle'] });
	    // if there are features within the given radius of the click event,
	    // fly to the location of the click event
	    if (features.length) {
        // Get coordinates from the symbol and center the map on those coordinates
        var center = features[0].geometry.coordinates;
        //this.map.flyTo({center: center});
        var id = features[0].properties.id;
        if(this.popup.isOpen&&this.popup.isOpen()){
        	this.popup.setLngLat(center);
        	this.popup.setText(this.searchResults[id].text);
        }else{
        	var popup = new mapboxgl.Popup({closeOnClick:false})
        	  .setLngLat(center)
        	  .setText(this.searchResults[id].text)
        	  .addTo(this.map);
        	this.popup = popup;
        }
	    }
		},
		mapClick:function (e) {
	    var scopeFeatures = this.map.queryRenderedFeatures(e.point, {filter:['==', 'type', 'scope']});
	    if(scopeFeatures.length) {
	    	var feature = scopeFeatures[0];
	    	var center = feature.geometry.coordinates;
	    	//this.map.flyTo({center: center});
	    	this.scopeProperties = feature.properties;
	    	/*var text = JSON.stringify(feature.properties,null,2);
	    	if(this.popup.isOpen&&this.popup.isOpen()){
	    		this.popup.setLngLat(center);
	    		this.popup.setText(text);
	    	}else{
	    		var popup = new mapboxgl.Popup({closeOnClick:false})
	    		  .setLngLat(center)
	    		  .setText(text)
	    		  .addTo(this.map);
	    		this.popup = popup;
	    	}*/
	    }
		},
		searchMouseMove:function(e) {
			var features = this.map.queryRenderedFeatures(e.point, { layers: ['searchResult-circle-stroke','searchResult-circle'] });
			this.map.getCanvas().style.cursor = features.length ? 'pointer' : '';
		},
		mapMouseMove:function (e) {
	    var scopeFeatures = this.map.queryRenderedFeatures(e.point, {filter:['==', 'type', 'scope']});
	    this.map.getCanvas().style.cursor = scopeFeatures.length ? 'pointer' : '';
		}
	},
	attached(){
		mapboxgl.accessToken = util.gl_accessToken;
		if (!mapboxgl.supported()){
			this.$Message.warning("抱歉，你的浏览器不支持webgl，无法显示地图！", 0)
		}else{
			this.$http({url:"/static/style.json",method:'GET'}).then(function(res){
				var style = res.data;
				var map = new mapboxgl.Map({
				  container: 'map-container',
				  style: style,
				  zoom:9,
				  center:[116,39.5],
				  attributionControl: false
				});
				var geocoder = new MapboxGeocoder({accessToken: util.gl_accessToken})
				map.addControl(new mapboxgl.NavigationControl(),"bottom-right");
				/*map.addControl(geocoder,"top-left");*/
				this.map = map;
				this.map.on("click",this.mapClick);
        this.map.on("mousemove",this.mapMouseMove);
			},function(res){});
		}
	},
	data(){
		return {
			map:{},
			searchKeyWords:"",
			searchResults:[],
			popup:{},
			scopeProperties:{}
		}
	}
}
	
</script>

<style scoped>
	#map-container{
		width: 100%;
		height: 100%;
	}
	.toolbar{
		position: absolute;
		right: 50px;
		top: 30px;
		background-color: white;
	}
	.locate{
		position: absolute;
		right: 10px;
		bottom: 120px;
		border-radius: 4px;
		background-color: white;
	}
	.search{
		position: absolute;
		top: 30px;
		left: 20px;
		background-color: white;
		padding: 5px;
	}
	#detail-panel{
		position: absolute;
		width: 300px;
		height: 400px;
		background-color: #fff;
		left: 10px;
		top: 100px;
	}
</style>